package com.papercutting.platform.controller;

import com.papercutting.platform.common.Result;
import com.papercutting.platform.entity.User;
import com.papercutting.platform.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/api/user")
@RequiredArgsConstructor
public class UserController {
    
    private final UserService userService;
    private final PasswordEncoder passwordEncoder;
    
    /**
     * 获取当前用户信息
     */
    private User getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated() && 
            !"anonymousUser".equals(authentication.getPrincipal())) {
            String username = authentication.getName();
            return userService.findByNickname(username);
        }
        return null;
    }
    
    /**
     * 获取用户列表（管理员）
     */
    @GetMapping("/list")
    public Result<Map<String, Object>> getUserList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) Integer userType,
            @RequestParam(defaultValue = "createTime") String orderBy) {
        
        // 检查用户权限
        User currentUser = getCurrentUser();
        System.out.println("当前用户信息: " + (currentUser != null ? currentUser.getNickname() + ", 类型: " + currentUser.getUserType() : "用户不存在"));
        
        if (currentUser == null) {
            return Result.error(401, "未授权访问，请先登录");
        }
        
        if (currentUser.getUserType() != 1) {
            return Result.error(403, "权限不足，只有管理员可以访问用户列表");
        }
        
        // 创建分页对象
        Sort sort = Sort.by(Sort.Direction.DESC, orderBy);
        Pageable pageable = PageRequest.of(page - 1, size, sort);
        
        // 查询数据
        Page<User> userPage = userService.findUserList(keyword, userType, pageable);
        
        // 构造返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("list", userPage.getContent());
        result.put("total", userPage.getTotalElements());
        result.put("page", page);
        result.put("size", size);
        result.put("totalPages", userPage.getTotalPages());
        
        return Result.success(result);
    }
    
    /**
     * 获取用户详情
     */
    @GetMapping("/{id}")
    public Result<User> getUserDetail(@PathVariable Long id) {
        // 检查用户权限
        User currentUser = getCurrentUser();
        if (currentUser == null) {
            return Result.error(401, "未授权访问，请先登录");
        }
        
        // 管理员可以查看所有用户，普通用户只能查看自己的信息
        if (currentUser.getUserType() != 1 && !currentUser.getId().equals(id)) {
            return Result.error(403, "权限不足，只能查看自己的信息");
        }
        
        User user = userService.findById(id);
        if (user == null) {
            return Result.error(404, "用户不存在");
        }
        return Result.success(user);
    }
    
    /**
     * 创建用户（管理员）
     */
    @PostMapping
    public Result<User> createUser(@Valid @RequestBody User user) {
        // 检查用户权限
        User currentUser = getCurrentUser();
        if (currentUser == null || currentUser.getUserType() != 1) {
            return Result.error(403, "权限不足，只有管理员可以创建用户");
        }
        
        // 检查用户名是否已存在
        User existingUser = userService.findByNickname(user.getNickname());
        if (existingUser != null) {
            return Result.error(400, "用户名已存在");
        }
        
        // 检查密码
        if (user.getPassword() == null || user.getPassword().isEmpty()) {
            return Result.error(400, "密码不能为空");
        }
        
        // 密码强度验证（至少6位）
        if (user.getPassword().length() < 6) {
            return Result.error(400, "密码长度至少6位");
        }
        
        // 设置默认值
        if (user.getStatus() == null) {
            user.setStatus(0); // 默认正常状态
        }
        
        if (user.getUserType() == null) {
            user.setUserType(0); // 默认普通用户
        }
        
        // 密码加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        
        // 设置创建时间
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        
        User savedUser = userService.save(user);
        return Result.success("用户创建成功", savedUser);
    }
    
    /**
     * 更新用户信息
     */
    @PutMapping("/{id}")
    public Result<User> updateUserInfo(@PathVariable Long id, @Valid @RequestBody User user) {
        // 检查用户权限
        User currentUser = getCurrentUser();
        if (currentUser == null) {
            return Result.error(401, "未授权访问，请先登录");
        }
        
        // 普通用户只能更新自己的信息，管理员可以更新所有用户信息
        if (currentUser.getUserType() != 1 && !currentUser.getId().equals(id)) {
            return Result.error(403, "权限不足，只能更新自己的信息");
        }
        
        if (!id.equals(user.getId())) {
            return Result.error(400, "用户ID不匹配");
        }
        
        // 查找数据库中的原始用户信息
        User originalUser = userService.findById(id);
        if (originalUser == null) {
            return Result.error(404, "用户不存在");
        }
        
        // 保留重要字段不被修改
        user.setOpenId(originalUser.getOpenId());
        user.setCreateTime(originalUser.getCreateTime());
        user.setUpdateTime(LocalDateTime.now());
        
        // 如果密码不为空，则进行加密
        if (user.getPassword() != null && !user.getPassword().isEmpty()) {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        } else {
            // 如果密码为空，保留原密码
            user.setPassword(originalUser.getPassword());
        }
        
        User updatedUser = userService.save(user);
        return Result.success(updatedUser);
    }
    
    /**
     * 删除用户
     */
    @DeleteMapping("/{id}")
    public Result<String> deleteUser(@PathVariable Long id) {
        // 检查用户权限
        User currentUser = getCurrentUser();
        if (currentUser == null || currentUser.getUserType() != 1) {
            return Result.error(403, "权限不足，只有管理员可以删除用户");
        }
        
        // 不能删除自己
        if (currentUser.getId().equals(id)) {
            return Result.error(400, "不能删除自己的账户");
        }
        
        User user = userService.findById(id);
        if (user == null) {
            return Result.error(404, "用户不存在");
        }
        
        userService.deleteById(id);
        return Result.success("用户删除成功");
    }
    
    /**
     * 获取当前用户信息
     */
    @GetMapping("/profile")
    public Result<User> getCurrentUserProfile() {
        User user = getCurrentUser();
        if (user == null) {
            return Result.error(401, "未授权访问，请先登录");
        }
        return Result.success(user);
    }
    
    /**
     * 更新当前用户信息
     */
    @PutMapping("/profile")
    public Result<User> updateCurrentUserProfile(@Valid @RequestBody User user) {
        User currentUser = getCurrentUser();
        if (currentUser == null) {
            return Result.error(401, "未授权访问，请先登录");
        }
        
        if (!currentUser.getId().equals(user.getId())) {
            return Result.error(400, "用户ID不匹配");
        }
        
        // 查找数据库中的原始用户信息
        User originalUser = userService.findById(currentUser.getId());
        if (originalUser == null) {
            return Result.error(404, "用户不存在");
        }
        
        // 保留重要字段不被修改
        user.setOpenId(originalUser.getOpenId());
        user.setNickname(originalUser.getNickname()); // 不允许修改用户名
        user.setUserType(originalUser.getUserType()); // 不允许修改用户类型
        user.setCreateTime(originalUser.getCreateTime());
        user.setUpdateTime(LocalDateTime.now());
        
        // 如果密码不为空，则进行加密
        if (user.getPassword() != null && !user.getPassword().isEmpty()) {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        } else {
            // 如果密码为空，保留原密码
            user.setPassword(originalUser.getPassword());
        }
        
        User updatedUser = userService.save(user);
        return Result.success(updatedUser);
    }
    
    /**
     * 获取用户统计信息
     */
    @GetMapping("/stats")
    public Result<Map<String, Object>> getUserStats() {
        // 检查用户权限
        User currentUser = getCurrentUser();
        if (currentUser == null || currentUser.getUserType() != 1) {
            return Result.error(403, "权限不足，只有管理员可以访问用户统计信息");
        }
        
        Map<String, Object> stats = userService.getUserStats();
        return Result.success(stats);
    }
    
    /**
     * 重置用户密码（管理员）
     */
    @PutMapping("/{id}/reset-password")
    public Result<String> resetUserPassword(@PathVariable Long id, @RequestBody Map<String, String> payload) {
        // 检查用户权限
        User currentUser = getCurrentUser();
        if (currentUser == null || currentUser.getUserType() != 1) {
            return Result.error(403, "权限不足，只有管理员可以重置用户密码");
        }
        
        String newPassword = payload.get("newPassword");
        if (newPassword == null || newPassword.isEmpty()) {
            return Result.error(400, "新密码不能为空");
        }
        
        // 密码强度验证（至少6位）
        if (newPassword.length() < 6) {
            return Result.error(400, "密码长度至少6位");
        }
        
        User user = userService.findById(id);
        if (user == null) {
            return Result.error(404, "用户不存在");
        }
        
        // 密码加密
        user.setPassword(passwordEncoder.encode(newPassword));
        user.setUpdateTime(LocalDateTime.now());
        userService.save(user);
        
        return Result.success("密码重置成功");
    }
    
    /**
     * 启用/禁用用户（管理员）
     */
    @PutMapping("/{id}/status")
    public Result<String> updateUserStatus(@PathVariable Long id, @RequestBody Map<String, Integer> payload) {
        // 检查用户权限
        User currentUser = getCurrentUser();
        if (currentUser == null || currentUser.getUserType() != 1) {
            return Result.error(403, "权限不足，只有管理员可以修改用户状态");
        }
        
        Integer status = payload.get("status");
        if (status == null || (status != 0 && status != 1)) {
            return Result.error(400, "状态值无效，只能是0（正常）或1（禁用）");
        }
        
        User user = userService.findById(id);
        if (user == null) {
            return Result.error(404, "用户不存在");
        }
        
        // 不能修改自己的状态
        if (currentUser.getId().equals(id)) {
            return Result.error(400, "不能修改自己的账户状态");
        }
        
        user.setStatus(status);
        user.setUpdateTime(LocalDateTime.now());
        userService.save(user);
        
        String statusText = status == 0 ? "启用" : "禁用";
        return Result.success("用户已" + statusText);
    }
}